# -*- coding:utf8 -*-
from peewee import *
import threading

threadLock = threading.Lock()
datadb = SqliteDatabase('data.db')


class BaseModel(Model):
    class Meta:
        database = datadb


class urls(BaseModel):
    id = PrimaryKeyField()
    url = CharField(null = False)
    fromurl = CharField(default='')
    deepth = IntegerField(default=0)
    savepath = CharField(default='')
    #type:'1为网页,2为资源，3为音视频，4为其他,5为列表'
    filetype = IntegerField(default=0)
    filestatus = IntegerField(default=0)
    fileflag = IntegerField(default=0)

    class Meta:
        db_table = 'urls'
        order_by = 'id'


    def addurl(self,url,**args):
        threadLock.acquire()
        model = None
        try:
            model = urls.get(urls.url==url,urls.savepath==args['savepath'])
        except Exception as e:
            pass
        finally:
            pass
        try:
            if model == None:
                self.create(url=url,**args)
        except:
            pass
        finally:
            threadLock.release()

    def popurl(self,type=0):
        threadLock.acquire()
        model = None
        left = 0
        try:
            if type==0:
                model = urls.get(urls.filestatus==0)
            else:
                model = urls.get(urls.filestatus==0 and urls.type==type)
            model.filestatus=5
            model.save()
            left = urls.select().where(urls.filestatus==0).count()
        except:
            pass
        finally:
            threadLock.release()
            return model,left

    def setstatus(self,id,filestatus):
        threadLock.acquire()
        try:
            urls.update(filestatus=filestatus).where(urls.id==id).execute()
        except:
            pass
        finally:
            threadLock.release()


